<template>
  <div class="game-container">

    
    <div class="game-header">
      <button 
        v-if="keySettings.showBackButton" 
        class="back-button" 
        @click="showExitConfirm = true" 
        tabindex="0" 
        ref="backButton"
      >
        返回
      </button>
      <h1 class="game-title">猜谜语游戏</h1>
    </div>
    
    <div class="game-content">
      
      <div class="riddle-layout" v-if="!gameOver">
        <div class="riddle-card" :class="{ 'timer-countdown': timeLeft > 0 }" v-if="currentRiddle" :style="timeLeft > 0 ? { '--timer-progress': timeLeft / 30 } : {}">
          <h2 class="riddle-question">{{ currentRiddle.question }}</h2>
          <div class="riddle-hint">
            <div class="hint-label">提示</div>
            <div class="hint-content" v-if="showHint">
              选项包含 {{ currentRiddle.answer.length }} 个字
            </div>
            <div class="hint-placeholder" v-else>
              倒计时过半时自动显示提示
            </div>
          </div>
          
          <!-- 选择题 -->
          <div class="options-container" v-if="currentRiddle.type_ === 'choice'">
            <button 
              v-for="(option, index) in parsedOptions" 
              :key="index"
              class="option-button"
              :class="{ 
                'selected': selectedOption === option,
                'correct': showAnswer && option === currentRiddle.answer,
                'incorrect': showAnswer && selectedOption === option && option !== currentRiddle.answer
              }"
              @click="selectOption(option)"
              :disabled="showAnswer"
              tabindex="0"
              ref="optionButtons"
            >
              {{ option }}
            </button>
          </div>
          
          <!-- 移除问答题UI，现在只有选择题 -->
          

        </div>

        <div class="timer-sidebar">
          <!-- 玩家积分对比 -->
          <div class="players-score-sidebar">
            <div class="score-title">积分对比</div>
            <div class="players-score-container">
              <div 
                class="player-score-item" 
                :class="{ active: currentPlayer === 1 }"
              >
                <div class="player-info">
                  <i class="fas fa-male player-icon"></i>
                  <span class="player-label">玩家1</span>
                </div>
                <div class="score-value">{{ player1Score }}</div>
                <div class="stats-detail">
                  <div class="stat-item correct">
                    <span class="stat-label">正确</span>
                    <span class="stat-value">{{ player1Stats.correct }}</span>
                  </div>
                  <div class="stat-item wrong">
                    <span class="stat-label">错误</span>
                    <span class="stat-value">{{ player1Stats.wrong }}</span>
                  </div>
                  <div class="stat-item timeout">
                    <span class="stat-label">超时</span>
                    <span class="stat-value">{{ player1Stats.timeout }}</span>
                  </div>
                </div>
              </div>
              <div class="vs-divider">VS</div>
              <div 
                class="player-score-item"
                :class="{ active: currentPlayer === 2 }"
              >
                <div class="player-info">
                  <i class="fas fa-female player-icon"></i>
                  <span class="player-label">玩家2</span>
                </div>
                <div class="score-value">{{ player2Score }}</div>
                <div class="stats-detail">
                  <div class="stat-item correct">
                    <span class="stat-label">正确</span>
                    <span class="stat-value">{{ player2Stats.correct }}</span>
                  </div>
                  <div class="stat-item wrong">
                    <span class="stat-label">错误</span>
                    <span class="stat-value">{{ player2Stats.wrong }}</span>
                  </div>
                  <div class="stat-item timeout">
                    <span class="stat-label">超时</span>
                    <span class="stat-value">{{ player2Stats.timeout }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 下一题按钮 -->
          <div class="next-button-container" v-if="showAnswer">
            <button 
              class="control-button next-button" 
              @click="nextTurn()"
              tabindex="0"
            >
              下一题
            </button>
          </div>
          
          <div class="player-turn">
            <div class="turn-value">{{ currentPlayerName }}</div>
          </div>
        </div>
      </div>
      
      <!-- 底部回合信息 -->
      <div class="bottom-round-info" v-if="!gameOver">
        <div class="round-display">
          {{ currentRound }} / {{ totalRounds }}
        </div>
      </div>
    </div> <!-- 添加 game-content 的闭合标签 -->
    
    <!-- 游戏结束 -->
    <div class="game-over" v-if="gameOver">
      <h2>游戏结束</h2>
      <div class="final-scores">
        <div class="final-score">
          <div class="player-name">玩家1</div>
          <div class="score">{{ player1Score }} 分</div>
        </div>
        <div class="vs">VS</div>
        <div class="final-score">
          <div class="player-name">玩家2</div>
          <div class="score">{{ player2Score }} 分</div>
        </div>
      </div>
      
      <div class="winner-announcement">
        <template v-if="player1Score > player2Score">
          <h3>玩家1 获胜！</h3>
        </template>
        <template v-else-if="player2Score > player1Score">
          <h3>玩家2 获胜！</h3>
        </template>
        <template v-else>
          <h3>平局！</h3>
        </template>
      </div>
      
      <button class="restart-button" @click="restartGame">重新游戏</button>
    </div>
    


    <!-- 退出确认对话框 -->
    <div class="modal-overlay" v-if="showExitConfirm" @click="showExitConfirm = false">
      <div class="modal-content" @click.stop>
        <h3>确认退出</h3>
        <p>您确定要退出当前游戏吗？游戏进度将会丢失。</p>
        <div class="modal-buttons">
          <button class="cancel-button" @click="showExitConfirm = false">取消</button>
          <button class="confirm-button" @click="exitGame">确认退出</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { safeInvoke } from '../utils/tauri';
import { getKeySettings, setupGlobalKeyHandlers, type KeySettings } from '../utils/keySettings';
import { showSuccess, showError } from '../utils/snackbar';

// 谜语类型已移至 tauri.ts 中处理

// 路由
const router = useRouter();

// 游戏状态
const currentRound = ref(1);
const totalRounds = ref(10);
const currentPlayer = ref(1);
const player1Score = ref(0);
const player2Score = ref(0);
const gameOver = ref(false);
const player1QuestionIndex = ref(0);
const player2QuestionIndex = ref(0);
const countdown = ref(0);
const showCountdown = ref(false);
const showExitConfirm = ref(false);

// 答题统计
const player1Stats = ref({
  correct: 0,
  wrong: 0,
  timeout: 0
});
const player2Stats = ref({
  correct: 0,
  wrong: 0,
  timeout: 0
});

// 按键设置
const keySettings = reactive<KeySettings>({
  showBackButton: true,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

// 答题倒计时
const timeLeft = ref(30); // 30秒答题时间
const timerInterval = ref<number | null>(null);
const countdownTimer = ref<number | null>(null);

// 提示功能
const showHint = ref(false);



// 当前谜语
const currentRiddle = ref<any>(null);
const selectedOption = ref('');
const showAnswer = ref(false);
const isCorrect = ref(false);

// 谜语队列
const player1Riddles = ref<any[]>([]);
const player2Riddles = ref<any[]>([]);

// 计算属性
const currentPlayerName = computed(() => `玩家${currentPlayer.value}`);

// 保留radius变量以备将来可能的SVG进度条实现
// const radius = ref(290); // 半径，稍小于卡片的一半

const parsedOptions = computed((): string[] => {
  if (!currentRiddle.value || !currentRiddle.value.options) return [];
  try {
    const parsed = JSON.parse(currentRiddle.value.options);
    return Array.isArray(parsed) ? parsed : [];
  } catch (e) {
    console.error('Failed to parse options:', e);
    return [];
  }
});

// 初始化游戏
async function initGame() {
  try {
    // 重置所有游戏的谜语使用状态
    await safeInvoke('reset_riddles_by_game', {
      request: { id: 1 }
    });
    await safeInvoke('reset_riddles_by_game', {
      request: { id: 2 }
    });
    
    // 为玩家1加载谜语（从猜谜语游戏表中获取，全部是选择题）
    const player1Riddles10 = await safeInvoke('get_unused_riddles', {
      request: { count: 10, game_id: 1 } // game_id=1 表示猜谜语(选择题)
    }) as any[];
    
    player1Riddles.value = player1Riddles10 || [];

    // 为玩家2也加载选择题（从猜谜语游戏表中获取，移除问答题）
    const player2Riddles10 = await safeInvoke('get_unused_riddles', {
      request: { count: 10, game_id: 1 } // 改为game_id=1，只使用选择题
    }) as any[];
    
    player2Riddles.value = player2Riddles10 || [];
    
    // 标记玩家1的谜语为已使用
    for (const riddle of player1Riddles.value) {
      await safeInvoke('mark_riddle_as_used', { 
        request: { 
          id: riddle.id,
          game_id: 1 
        } 
      });
    }
    
    // 标记玩家2的谜语为已使用（现在也是选择题）
    for (const riddle of player2Riddles.value) {
      await safeInvoke('mark_riddle_as_used', { 
        request: { 
          id: riddle.id,
          game_id: 1 // 改为game_id=1，因为现在都是选择题
        } 
      });
    }
    
    // 开始第一轮
    startTurn();
  } catch (error) {
    console.error('Failed to initialize game:', error);
  }
}

/**
 * 开始当前回合
 * 重置所有状态并准备新题目，但不立即开始倒计时
 */
function startTurn() {
  // 重置所有答题相关状态
  selectedOption.value = '';
  showAnswer.value = false;
  showCountdown.value = false;
  countdown.value = 0;
  showHint.value = false;
  
  // 清除所有计时器
  clearAllTimers();
  
  // 获取当前玩家的谜语和题目索引
  const riddles = currentPlayer.value === 1 ? player1Riddles.value : player2Riddles.value;
  const questionIndex = currentPlayer.value === 1 ? player1QuestionIndex.value : player2QuestionIndex.value;
  
  // 如果已经没有谜语了，游戏结束
  if (questionIndex >= riddles.length) {
    gameOver.value = true;
    return;
  }
  
  // 设置当前谜语
  currentRiddle.value = riddles[questionIndex];
  
  // 延迟开始答题倒计时，确保UI更新完成
  setTimeout(() => {
    startAnswerTimer();
  }, 100);
}

/**
 * 清除所有计时器
 */
function clearAllTimers() {
  if (timerInterval.value !== null) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
  
  if (countdownTimer.value !== null) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
}

/**
 * 开始答题倒计时
 * 重置倒计时并开始新的计时器
 */
function startAnswerTimer() {
  // 重置倒计时时间
  timeLeft.value = 30;
  
  // 确保之前的计时器已清除
  if (timerInterval.value !== null) {
    clearInterval(timerInterval.value);
  }
  
  // 开始新的倒计时
  timerInterval.value = setInterval(() => {
    timeLeft.value--;
    
    // 当剩余时间为一半时自动显示提示
    if (timeLeft.value === 15 && !showHint.value) {
      showHint.value = true;
    }
    
    // 时间到
    if (timeLeft.value <= 0) {
      clearInterval(timerInterval.value as number);
      timerInterval.value = null;
      // 时间到，视为回答错误
      handleTimeUp();
    }
  }, 1000) as unknown as number;
}

// 处理时间到的情况
function handleTimeUp() {
  showAnswer.value = true;
  isCorrect.value = false;
  
  // 更新超时统计
  if (currentPlayer.value === 1) {
    player1Stats.value.timeout += 1;
  } else {
    player2Stats.value.timeout += 1;
  }
  
  // 显示超时消息
  showError(`时间到! 正确答案: ${currentRiddle.value.answer}`);
  
  // 延迟开始切换倒计时，给用户时间查看结果
  setTimeout(() => {
    startCountdown();
  }, 2000);
}

/**
 * 选择选项（选择题）
 */
function selectOption(option: string) {
  if (showAnswer.value) return;
  
  // 停止答题倒计时
  if (timerInterval.value !== null) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
  
  selectedOption.value = option;
  checkAnswer(); // checkAnswer函数会处理消息显示
}

// 移除submitAnswer函数，因为现在只有选择题

/**
 * 检查答案并处理结果
 */
function checkAnswer() {
  showAnswer.value = true;
  
  // 判断答案是否正确（现在只有选择题）
  isCorrect.value = selectedOption.value === currentRiddle.value.answer;
  
  // 更新分数和统计
  if (isCorrect.value) {
    if (currentPlayer.value === 1) {
      player1Score.value += 1;
      player1Stats.value.correct += 1;
    } else {
      player2Score.value += 1;
      player2Stats.value.correct += 1;
    }
  } else {
    // 答错了
    if (currentPlayer.value === 1) {
      player1Stats.value.wrong += 1;
    } else {
      player2Stats.value.wrong += 1;
    }
  }
  
  // 显示结果消息
  if (isCorrect.value) {
    showSuccess('回答正确! +1分');
  } else {
    showError(`回答错误! 正确答案: ${currentRiddle.value.answer}`);
  }
  
  // 延迟开始切换倒计时，给用户时间查看结果
  setTimeout(() => {
    startCountdown();
  }, 2000); // 减少到2秒，提高游戏节奏
}

// 开始倒计时
function startCountdown() {
  countdown.value = 3;
  showCountdown.value = true;
  
  // 清除之前的倒计时计时器
  if (countdownTimer.value !== null) {
    clearInterval(countdownTimer.value);
  }
  
  countdownTimer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value as number);
      countdownTimer.value = null;
      showCountdown.value = false;
      nextTurn();
    }
  }, 1000) as unknown as number;
}

// 下一回合
function nextTurn() {
  // 如果当前是玩家1，增加玩家1的题目索引并切换到玩家2
  if (currentPlayer.value === 1) {
    player1QuestionIndex.value += 1;
    currentPlayer.value = 2;
  } else {
    // 如果当前是玩家2，增加玩家2的题目索引，切换到玩家1并增加轮数
    player2QuestionIndex.value += 1;
    currentPlayer.value = 1;
    currentRound.value += 1;
  }
  
  // 检查游戏是否结束
  if (currentRound.value > totalRounds.value) {
    gameOver.value = true;
    return;
  }
  
  // 开始新回合
  startTurn();
}

// 重新开始游戏
function restartGame() {
  // 重置游戏状态
  currentRound.value = 1;
  currentPlayer.value = 1;
  player1Score.value = 0;
  player2Score.value = 0;
  gameOver.value = false;
  player1QuestionIndex.value = 0;
  player2QuestionIndex.value = 0;
  
  // 重置统计数据
  player1Stats.value = { correct: 0, wrong: 0, timeout: 0 };
  player2Stats.value = { correct: 0, wrong: 0, timeout: 0 };
  
  // 初始化游戏
  initGame();
}

// 退出游戏
function exitGame() {
  router.push('/');
}

// 键盘事件处理
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape') {
    showExitConfirm.value = true;
  }
};

// 右键菜单事件处理
const handleContextMenu = (e: MouseEvent) => {
  e.preventDefault();
  showExitConfirm.value = true;
};

// 加载按键设置的函数
const loadKeySettings = async () => {
  const settings = await getKeySettings();
  Object.assign(keySettings, settings);
};

// 页面获得焦点时重新加载设置
const handleVisibilityChange = () => {
  if (!document.hidden) {
    loadKeySettings();
  }
};

// 组件挂载时初始化游戏和事件监听
onMounted(async () => {
  // 初始加载按键设置
  await loadKeySettings();
  
  // 设置全局按键处理器
  const cleanup = setupGlobalKeyHandlers(keySettings, {
    onEscape: () => { showExitConfirm.value = true; },
    onContextMenu: handleContextMenu,
    onKeyDown: keySettings.enableKeyboardNavigation ? handleKeyDown : undefined
  });
  
  // 监听页面可见性变化，当页面重新获得焦点时重新加载设置
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 添加右键菜单监听
  window.addEventListener('contextmenu', handleContextMenu);
  
  // 初始化游戏
  initGame();
  
  // 组件卸载时清理
  onUnmounted(() => {
    cleanup();
    document.removeEventListener('visibilitychange', handleVisibilityChange);
    window.removeEventListener('contextmenu', handleContextMenu);
    // 清理所有计时器
    clearAllTimers();
  });
});
</script>

<style scoped lang="scss">
@use './RiddleGame.scss';
</style>